<template>
  <div class="root"
       @touchstart="touchstartHandler"
       @touchmove="touchmoveHandler"
       @touchend="touchendHandler"
   >
    <div class="letter"
         v-for="(letter, index) of letters"
         :key="letter"
         @click="clickHandler"
         :ref="'letter-' + index">
       {{letter}}
    </div>
  </div>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    letters: {
      type: Array,
      required: true,
      default () {
        return []
      }
    }
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  updated () {
    this.startY = this.$refs['letter-0'][0].offsetTop
  },
  methods: {
    touchstartHandler () {
      this.touchStatus = true
    },
    touchmoveHandler (e) {
      if (this.touchStatus) {
        if (this.timer) {
          clearTimeout(this.timer)
        }
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY
          const index = Math.floor((touchY - this.startY - 84) / 20)
          if (index >= 0 && index < this.letters.length) {
            this.$emit('letterChange', this.letters[index])
          }
        }, 15)
      }
    },
    touchendHandler () {
      this.touchStatus = false
    },
    clickHandler (e) {
      this.$emit('letterChange', e.target.innerText)
    }
  }
}
</script>

<style lang="stylus" scoped>
.root
  position: fixed
  display: flex
  flex-direction: column
  justify-content: center
  top: 1.68rem
  bottom: 0
  right: 0
  width: .6rem
  .letter
    width: 100%
    text-align: center
    line-height: .4rem
</style>
